#include "client.h"

int main(int argc, char *argv[])
{
    // ./client 192.168.171.12 1234
    ARGS_CHECK(argc, 3);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);

    int ret = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
    ERROR_CHECK(ret,-1,"connect");

    printf("Link Start!\n\n");
    
    int isLogin = 0;
    while (1)
    {
            char buf[4096];
            bzero(buf, sizeof(buf));
            if(isLogin == 0)
            {
                printf("login or regist --------------\n\n");
                ssize_t sret = read(STDIN_FILENO, buf, sizeof(buf));
                if(buf[strlen(buf) - 1] == '\n')
                {
                    buf[strlen(buf) - 1] = '\0';
                }
                int length = strlen(buf);
                send(sockfd, buf, length, 0);
                if((strcmp(buf, "login")) == 0)
                {
                    printf("now do login\n");
                    c_login(sockfd, &isLogin);
                }
                else if((strcmp(buf, "regist")) == 0)
                {
                    printf("now do regist\n");
                    c_regist(sockfd);
                    continue;
                }
                printf("login successful\n");
            }

            if(isLogin == 1)
            {
                printf("Please input command:\n");
                bzero(buf, sizeof(buf));
                ssize_t sret = read(STDIN_FILENO, buf, sizeof(buf));
                if(sret == 0)
                {
                    send(sockfd, "客户端已断开！\n", 16, 0);
                    break;
                }
                send(sockfd, buf, sret, 0);
                client_worker(sockfd, buf);
            }
    }    

    close(sockfd);
    return 0;

}
